#!/opt/bin/python2.6

import sys, urllib,os
sys.path.append("/volume1/dev/python/lib")
import cgi,re
from time import time
from datetime import datetime, timedelta
from shutil import copy


arguments  = cgi.FieldStorage()

print "Content-Type: text/html"
print
print """
<!DOCTYPE html>
<html>
<head>
        <title>Domotique Paillet</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
        <link rel="stylesheet" href="/media/css/ced_mobile.css" />
        <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
        <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
</head>
<body>
"""
print "doing"
typejour = 0
hour = 0
day = 0

try: 
	typejour = int(arguments['typejour'].value)
	hour = int(arguments['hour'].value)
	day = int(arguments['day'].value)
except:
	print "goto default"
	
try:

	file_temp = '/volume1/dev/confile/conf-'+str(int(time()))+'.txt'

	fichier_w = open(file_temp, "w")
	fichier_r = open("/volume1/dev/confile/conf.txt", "r")
	splitter = re.compile('\#|\;')

	new_time =  datetime.now() + timedelta(hours=hour, days =day)

	print 'f;'+str(typejour)+';'+str(new_time.year)+';'+str(new_time.month)+';'+str(new_time.day)+';'+str(new_time.hour)+';'+str(new_time.minute)

	for ligne in fichier_r:
		donnees = splitter.split(ligne)
		if donnees[0] == 'f':
			fichier_w.writelines( 'f;'+str(typejour)+';'+str(new_time.year)+';'+str(new_time.month)+';'+str(new_time.day)+';'+str(new_time.hour)+';'+str(new_time.minute)+'\r\n')
		else:
			fichier_w.writelines(ligne)
	fichier_r.close()
	fichier_w.close()

	copy(file_temp,'/volume1/dev/confile/conf.txt')

	urllib.urlopen('http://192.168.1.4/ftp')
	print "end"
	print '<div><a href="/chauf/index_mob.cgi?toto=1">retour home</a></div>'
	print """</body>
	</html>
	"""
except:
	exc_type, exc_obj, exc_tb = sys.exc_info()
	#fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] 
	print( sys.exc_info(), exc_tb.tb_lineno)
	raise
